var util = require('../../utils/util.js');
var api = require('../../config/api.js');
// var Map = require("../../utils/map.js");
const App = getApp();
// 获取地图的返回信息
// const chooseLocation = requirePlugin('chooseLocation');

const BACK = "http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/Leader/id_bg.png",
    POSITIVE = "http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/Leader/id_country.png",
    LINCENCE = "http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/Leader/Licence.png";
Page({
    /**
     * 页面的初始数据
     */
    data: {
		// region: ['广东省', '广州市', '海珠区'],
        region: [],
        isClearShow: false,
        hasStorefront: true,
        // address: data.id,
        back: BACK, //反面身份证
        // hasStorefront: true,
        // lat: 0,
        // leaderName: 0,
        // lon: 0,
        // memberId: 0,
        // phone: 0,
        positive: POSITIVE, //正面身份证
        licence: LINCENCE, //营业照
        personSign: "", //签名照
        // username: "",
        // village: "",
        showPhoneValid: false,
        phone: "",
        location: {
            latitude: 0,
            longitude: 0
        },
        mapName: "",
        mapDetail: "",
        info: {}
	},

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getData();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // const location = chooseLocation.getLocation();
        // if(location){
        //     let mapName = location.province + location.city + location.district;
            
        //     console.log("123");
        //     if(!mapName){
        //         mapName = location.address.split(location.name)[0] || ""
        //     }
        //     const mapDetail = location.address.split(location.district)[1] + location.name;
        //     this.setData({
        //         location,
        //         mapName: mapName || "",
        //         mapDetail: mapDetail || ""
        //     })
        // }
        if(App.globalData.personSign){
            this.setData({
                personSign: App.globalData.personSign || ""
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        // chooseLocation.setLocation(null);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    // 地图事件
    toMap(){
        Map.getAddress(this.data.location);
    },
    // 手机事件 开始
    clearHide: function(e){
        const value = this.data.phone;
        if(!(/^1[0-9]{10}$/.test(value))){
            this.setData({
                showPhoneValid: true,
            })
        }else{
            if(this.data.showPhoneValid){
                this.setData({
                    showPhoneValid: false
                })
            }
        }
        this.setData({
            isClearShow: false,
        })
    },
    clearShow: function(e){
        this.setData({
            showPhoneValid: false,
            isClearShow: true,
        })
    },
    clearPhone: function(e){
        this.setData({
            phone: ""
        })
    },
    phoneInput: function(e){
        this.setData({
            phone: e.detail.value
        })
    },
    // 手机事件 结束

    radioChange: function(e){
        this.setData({
            hasStorefront: e.detail.value == 1 ? true : false
        })
    },
    // 后台请求
    applyMember(data){
        wx.showLoading({
            title: "正在提交中",
            icon: "none"
        })
        util.request(
            api.surroundings.applyStoreRealName,
            data,
            "POST"
        ).then(res=>{
            console.log("ress", res);
            wx.hideLoading();
            wx.showToast({
                title: "提交成功，正在审核",
                icon: "none"
            })
            this.payDeposit();
        }).catch(err=>{
            console.log("err", err);
            wx.hideLoading();
            wx.showToast({
                title: err.message,
                icon: "none"
            })
        })
    },
    // 提交表单
    formSubmit: function(e){
        const result = this.validForm(e.detail.value);
        if(result){
            // 验证成功
            const data = this.getParams(e.detail.value);
            this.applyMember(data);
        }
    },
    // 表单验证
    validForm(values){
        const { back, positive, licence, personSign } = this.data;
        if(licence === LINCENCE){
            wx.showToast({
                title: "营业照还没上传完哦",
                icon: "none"
            })
            return false;
        }
        if(back === BACK || positive === POSITIVE){
            wx.showToast({
                title: "身份证还没上传完哦",
                icon: "none"
            })
            return false;
        }
        if(personSign === ""){
            wx.showToast({
                title: "还没签名哦",
                icon: "none"
            })
            return false;
        }
        return true;
    },
    // 参数处理
    getParams(values){
        const { licence, back, positive, personSign, info } = this.data;
        const userInfo = wx.getStorageSync("userInfo");
        let defaultData = {
            "backCard": back,
            "businessLicense": licence,
            "merchantId": userInfo.merchantId,
            "personSign": personSign,
            "positiveCard": positive,
            "id": info.id
        };
        return Object.assign(defaultData, values)
    },
    // 预览图片
    gotoShow: function(e){
        const _this = this;
        const {type} = e.currentTarget.dataset;
        wx.chooseImage({
            count: 1, // 最多可以选择的图片张数，默认9
            sizeType: ['compressed'], // original 原图，compressed 压缩图，默认二者都有
            sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
            success: function(res){
                // success
                wx.showLoading({
                    title: "正在上传中"
                })
                wx.uploadFile({
                    url: api.leader.uploadImageUrl, //仅为示例，非真实的接口地址
                    filePath: res.tempFilePaths[0],
                    name: 'file',
                    formData: {
                      'user': type
                    },
                    success (result){
                        wx.hideLoading();
                        if(result.statusCode === 413){
                            return wx.showToast({
                                title: "图片太大了",
                                icon: "error"
                            })
                        }
                        result.data = JSON.parse(result.data);
                        const data = result.data.message;
                        _this.setData({
                            [type]: data
                        })
                    }
                })
            },
            fail: function() {
                // fail
            },
            complete: function() {
            // complete
            }
        })
    },
    payDeposit: function(param){
        const _this = this;
        wx.showLoading({
            title: "正在申请",
        })
    
        const userInfo = wx.getStorageSync("userInfo");
        util.request(api.surroundings.payDeposit + this.data.info.id, {}, "POST").then(res=>{
            const data = res.result;
            wx.requestPayment({
                timeStamp: data.timeStamp,
                nonceStr: data.nonceStr,
                package: data.packageValue,
                signType: data.signType,
                paySign: data.paySign,
                success (res) { 
                    wx.hideLoading();
                    wx.showToast({
                        title: "支付成功",
                        icon: "success"
                    })
                    setTimeout(()=>{
                        wx.navigateBack();
                    },2000);
                },
                fail (res) { 
                    wx.hideLoading()
                    wx.showToast({
                        title: "支付失败",
                        icon: "none"
                    })
                }
            })
        })
    },
    getData(){
        wx.showLoading({
            title: "正在加载",
        })
        util.request(api.surroundings.getStoreRealName, {}, "POST").then(res=>{
            console.log(res.result, "12");
            const data = res.result;
            this.setData({
                back: data.backCard || BACK,
                licence: data.businessLicense || LINCENCE,
                personSign: data.personSign || "",
                positive: data.positiveCard || POSITIVE,
                info: data,
            })
            wx.hideLoading();
        })
    }
});
